package org.tis.tools.senior.module.developer.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.senior.module.core.config.SvnProperties;
import org.tis.tools.senior.module.developer.controller.request.ProfileAddAndUpdateRequest;
import org.tis.tools.senior.module.developer.controller.request.ProfileAndBranchAddRequest;
import org.tis.tools.senior.module.developer.controller.request.ProfileUpdateIsRepeal;
import org.tis.tools.senior.module.developer.dao.SProfilesMapper;
import org.tis.tools.senior.module.developer.entity.*;
import org.tis.tools.senior.module.developer.entity.enums.*;
import org.tis.tools.senior.module.developer.entity.vo.*;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.*;
import org.tmatesoft.svn.core.SVNException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * sProfiles的Service接口实现类
 * 
 * @author Auto Generate Tools
 * @date 2018/06/20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SProfilesServiceImpl extends ServiceImpl<SProfilesMapper, SProfiles> implements ISProfilesService {

    @Autowired
    private ISBranchService branchService;

    @Autowired
    private ISBranchMappingService branchMappingService;

    @Autowired
    private ISDeliveryService deliveryService;

    @Autowired
    private ISSvnKitService svnKitService;

    @Autowired
    private ISProjectService projectService;

    @Autowired
    private SvnProperties svnProperties;

    @Autowired
    private ISWorkitemService workitemService;

    @Autowired
    private ISDeliveryListService deliveryListService;

    @Autowired
    private ISCheckService checkService;

    @Autowired
    private ISRepealService repealService;

    @Autowired
    private ISRepealListService repealListService;

    @Autowired
    private ISStandardListService standardListService;

    @Override
    public void add(ProfileAddAndUpdateRequest request) {
        SProfiles sProfiles = new SProfiles();
        BeanUtils.copyProperties(request,sProfiles);
        EntityWrapper<SProfiles> wrapper = new EntityWrapper<>();
        wrapper.eq(SProfiles.COLUMN_SERIAL_TAG, sProfiles.getSerialTag());
        if (selectCount(wrapper) > 0) {
            throw new DeveloperException("流水标志" + sProfiles.getSerialTag()  + "已存在");
        }
        sProfiles.setProfilesCode(sProfiles.getProfilesName());
        sProfiles.setIsAllowDelivery(IsAllowDelivery.ALLOW);
        sProfiles.setIsRepeal("false");

        List<String> count = new ArrayList<>();
        JSONArray jsonArray = JSONArray.parseArray(sProfiles.getPackTiming());
        for (Object object:jsonArray){
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            String isOpen = jsonObject.getString("isOpen");
            if(isOpen.equals(false)){
                count.add(isOpen);
            }
        }
        if(count.size() == jsonArray.size()){
            //修改运行环境状态
            sProfiles.setIsAllowDelivery(IsAllowDelivery.NOTALLOW);
        }
        insert(sProfiles);
    }

    @Override
    public void update(ProfileAddAndUpdateRequest request) {
        //将请求传入的值copy到新创建的对象中
        SProfiles sProfiles = new SProfiles();
        BeanUtils.copyProperties(request,sProfiles);
        sProfiles.setProfilesCode(sProfiles.getProfilesName());
        //查询是否有其他环境使用此流水标志
        EntityWrapper<SProfiles> wrapper = new EntityWrapper<>();
        wrapper.eq(SProfiles.COLUMN_SERIAL_TAG, sProfiles.getSerialTag())
                .ne(SProfiles.COLUMN_GUID, sProfiles.getGuid());
        if (selectCount(wrapper) > 0) {
            throw new DeveloperException("流水标志" + sProfiles.getSerialTag()  + "已存在");
        }
        //获取此环境中所有关闭的窗口
        List<String> count = new ArrayList<>();
        JSONArray jsonArray = JSONArray.parseArray(sProfiles.getPackTiming());
        for (Object object:jsonArray){
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            String isOpen = jsonObject.getString("isOpen");
            if(isOpen.equals("false")){
                count.add(isOpen);
            }
        }
        //判断此环境关闭的窗口是否等于此环境所创建的窗口个数
        if(count.size() == jsonArray.size()){
            //将环境状态设置为不允许投放
            sProfiles.setIsAllowDelivery(IsAllowDelivery.NOTALLOW);
        }else{
            //将环境状态设置为允许投放
            sProfiles.setIsAllowDelivery(IsAllowDelivery.ALLOW);
        }
        updateById(sProfiles);


    }

    @Override
    public List<SProfiles> selectProfilesAll() {
        //查询所有开启的环境
        EntityWrapper<SProfiles> spEntityWrapper = new EntityWrapper<>();
        spEntityWrapper.eq(SProfiles.COLUMN_IS_ALLOW_DELIVERY,IsAllowDelivery.ALLOW);

        return selectList(spEntityWrapper);
    }

    @Override
    public List<SProfiles> profilesAll() {
        List<SProfiles> profiles = selectProfilesAll();
        profiles.forEach(profile ->{
            JSONArray jsonArray  = JSONArray.parseArray(profile.getPackTiming());
            String str = "";
            for (Object object:jsonArray){
                JSONObject jsonObject = JSONObject.parseObject(object.toString());
                if(jsonObject.getString("isOpen").equals(PackTimeIsOpen.TRUE.getValue())){
                    if("".equals(str)){
                        str = jsonObject.getString("time");
                    }else{
                        str = str + "," + jsonObject.getString("time");
                    }
                }
            }
            profile.setPackTiming(str);
        });
        return profiles;
    }

    @Override
    public SProfiles selectOneById(Integer guidProfile) {
        SProfiles profiles = selectById(guidProfile);
        return profiles;
    }

    @Override
    public void insertProfileAndBranch(ProfileAndBranchAddRequest request) {
        SProfiles profiles = new SProfiles();
        BeanUtils.copyProperties(request.getProfileAddRequest(),profiles);
        profiles.setProfilesCode(profiles.getProfilesName());
        profiles.setIsAllowDelivery(IsAllowDelivery.ALLOW);
        insert(profiles);

        SBranch branch = new SBranch();
        BeanUtils.copyProperties(request.getBranchAddRequest(),branch);
        branchService.insert(branch);

        SBranchMapping branchMapping = new SBranchMapping();
        branchMapping.setGuidBranch(branch.getGuid());
        branchMapping.setForWhat(BranchForWhat.WORKITEM);
        branchMapping.setGuidOfWhats(profiles.getGuid());
        branchMapping.setAllotTime(new Date());
        branchMapping.setStatus(BranchMappingStatus.TAKE);
        branchMappingService.insert(branchMapping);
    }

    @Override
    public void deleteProfileAndBranchMapping(Integer profileGuid) {
        SProfiles profiles = selectById(profileGuid);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息详情!");
        }
        //查询此环境的分支信息
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,profileGuid);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT, BranchForWhat.RELEASE);
        List<SBranchMapping> sBranchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if (sBranchMappings.size() > 0) {
            throw new DeveloperException("此运行环境有关联的分支，请取消关联后，再删除！");
        }
        //查询此环境是否有投放过申请
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_PROFILES,profileGuid);
        if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
            throw new DeveloperException("此运行环境有投放申请，不允许删除！");
        }
        //删除guid对应的运行环境对象
        deleteById(profileGuid);
    }

    @Override
    public void updateProfileStatus(Integer profileGuid, IsAllowDelivery isAllowDelivery) {
        SProfiles profiles = selectById(profileGuid);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息详情!");
        }
        if(IsAllowDelivery.NOTALLOW.equals(isAllowDelivery)){
            EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
            deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_PROFILES, profileGuid);
            deliveryEntityWrapper.ne(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.DELIVERED);
            deliveryEntityWrapper.ne(SDelivery.COLUMN_DELIVERY_RESULT, DeliveryResult.FAILED);
            if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
                throw new DeveloperException("此运行环境还有投放申请未完成投放，不允许关闭！");
            }
        }
        profiles.setIsAllowDelivery(isAllowDelivery);
        updateById(profiles);
    }

    @Override
    public void insertProfileBranchMapping(ProfileAddAndUpdateRequest request, Integer guidBranch) {
        SProfiles sProfiles = new SProfiles();
        BeanUtils.copyProperties(request,sProfiles);
        sProfiles.setIsAllowDelivery(IsAllowDelivery.ALLOW);
        insert(sProfiles);

        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_BRANCH,guidBranch);
        List<SBranchMapping> sbmList = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sbmList.size() > 0){
            throw new DeveloperException("此分支已被指配，请重新选择分支！");
        }
        SBranchMapping branchMapping = new SBranchMapping();
        branchMapping.setGuidBranch(guidBranch);
        branchMapping.setForWhat(BranchForWhat.RELEASE);
        branchMapping.setGuidOfWhats(sProfiles.getGuid());
        branchMapping.setAllotTime(new Date());
        branchMapping.setStatus(BranchMappingStatus.TAKE);
        branchMappingService.insert(branchMapping);
    }

    @Override
    public void profileRelevanceBranch(Integer guidProfile, Integer guidBranch) {
        SProfiles profiles = selectById(guidProfile);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息详情!");
        }
        //查询此分支是否有被关联
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_BRANCH,guidBranch);
        List<SBranchMapping> sBranchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sBranchMappings.size() > 0){
            throw new DeveloperException("此分支已被指配，请重新选择分支！");
        }
        //查询此环境是否已有关联的分支信息
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper2 = new EntityWrapper<>();
        branchMappingEntityWrapper2.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,guidProfile);
        branchMappingEntityWrapper2.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.RELEASE);
        List<SBranchMapping> sBranchMappings2 = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sBranchMappings2.size() > 0){
            throw new DeveloperException("此运行环境已有关联分支！");
        }
        //新增分支关联信息表
        SBranchMapping branchMapping = new SBranchMapping();
        branchMapping.setGuidBranch(guidBranch);
        branchMapping.setForWhat(BranchForWhat.RELEASE);
        branchMapping.setGuidOfWhats(guidProfile);
        branchMapping.setAllotTime(new Date());
        branchMapping.setStatus(BranchMappingStatus.TAKE);
        branchMappingService.insert(branchMapping);
    }

    @Override
    public void profileCancelBranch(Integer guidProfile) {
        SProfiles profiles = selectById(guidProfile);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息详情!");
        }
        //查询此环境是否已有关联的分支信息
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,guidProfile);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.RELEASE);
        List<SBranchMapping> sbmList = branchMappingService.selectList(branchMappingEntityWrapper);
        if(sbmList.size() != 1){
            throw new DeveloperException("此运行环境没有分配分支,请关联分支！");
        }

        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_PROFILES, guidProfile);
        deliveryEntityWrapper.ne(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.DELIVERED);
        deliveryEntityWrapper.ne(SDelivery.COLUMN_DELIVERY_RESULT, DeliveryResult.FAILED);
        if(deliveryService.selectList(deliveryEntityWrapper).size() > 0){
            throw new DeveloperException("此运行环境关联的分支有投放申请，不允许取消关联！");
        }

        SBranchMapping branchMapping = sbmList.get(0);
        branchMappingService.deleteById(branchMapping.getGuid());
    }

    @Override
    public SBranch selectBranchByProfileGuid(Integer profileGuid) {
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,profileGuid);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT,BranchForWhat.RELEASE);
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() != 1){
            throw new DeveloperException("此运行环境没有分配分支信息！");
        }
        SBranchMapping branchMapping = branchMappings.get(0);
        return branchService.selectById(branchMapping.getGuidBranch());
    }

    @Override
    public List<SBranch> mayRelevanceReleaseBranch() {

        List<SBranchMapping> sBranchMappings = branchMappingService.selectList(null);
        List<Integer> branchGuid = new ArrayList<>();
        if(sBranchMappings.size() > 0) {
            for (SBranchMapping branchMapping : sBranchMappings) {
                branchGuid.add(branchMapping.getGuidBranch());
            }
            if (branchGuid.size() == 0) {
                throw new DeveloperException("没有查询到未被指配的分支");
            }
        }
        EntityWrapper<SBranch> branchEntityWrapper = new EntityWrapper<>();
        branchEntityWrapper.notIn(SBranch.COLUMN_GUID,branchGuid);
        branchEntityWrapper.eq(SBranch.COLUMN_BRANCH_TYPE,BranchType.RELEASE);
        return branchService.selectList(branchEntityWrapper);
    }

    @Override
    public Page<ProfileBranchDetail> profileFullPathDetail(Page<ProfileBranchDetail> page,
                                                           EntityWrapper<ProfileBranchDetail> wrapper) {

        return page.setRecords(this.baseMapper.selectProfileDetail(page,wrapper));
    }

    @Override
    public SProfiles validateProfiles(String profileId, String packTiming) {
        SProfiles profiles = this.baseMapper.selectById(profileId);
        if (profiles == null || !profiles.getPackTiming().contains(packTiming)) {
            throw new DeveloperException(profileId + "对应的环境或打包窗口" + packTiming + "不存在!");
        }
        return profiles;
    }

    @Override
    public List<SProfileDetail>  profileAllPackTimeVerify(Integer guidWorkitem) {
        List<SProfiles> profiles = selectProfilesAll();
        EntityWrapper<SDelivery> delisEntityWrapper = new EntityWrapper<>();
        delisEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, guidWorkitem);
        delisEntityWrapper.groupBy(SDelivery.COLUMN_GUID_PROFILES);
        List<SDelivery> deliveries = deliveryService.selectList(delisEntityWrapper);

        List<Integer> guidProfiles = deliveries.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());

        //查询此工作项今天的所有核对记录
        EntityWrapper<SCheck> checkEntityWrapper = new EntityWrapper<>();
        checkEntityWrapper.in(SCheck.COLUMN_GUID_PROFILES, guidProfiles);
        checkEntityWrapper.eq("DATE_FORMAT(" + SDelivery.COLUMN_DELIVERY_TIME + ", '%Y-%m-%d')",
                new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        List<SCheck> checks = checkService.selectList(checkEntityWrapper);

        List<SProfileDetail> sProfileDetails = new ArrayList<>();
        //循环所有可投放的环境
        profiles.forEach(pro -> {
            List<SCheck> sChecks = checks.stream().filter(check ->
                    pro.getGuid().equals(check.getGuidProfiles())).collect(Collectors.toList());
            SProfileDetail sProfileDetail = new SProfileDetail();
            PackTimeVerify packTimeVerify = null;
            try {
                packTimeVerify = packTimeVerify(pro.getPackTiming(),sChecks);
            } catch (ParseException e) {
                throw new DeveloperException("此"+pro.getProfilesName()+"的窗口不是时间格式!");
            }
            if(packTimeVerify == null){
                throw new DeveloperException("找不到此投放申请运行环境的打包窗口!");
            }
            sProfileDetail.setDeliveryTime(packTimeVerify.getDeliveryTime());
            sProfileDetail.setGuidProfile(pro.getGuid());
            sProfileDetail.setProfilesName(pro.getProfilesName());
            sProfileDetail.setPackTimeDetails(packTimeVerify.getPackTimeDetails());
            sProfileDetails.add(sProfileDetail);
        });

        List<Integer> guidProfile = new ArrayList<>();
        SWorkitem workitem = workitemService.selectById(guidWorkitem);
        if(workitem != null){
            //查询这个工作项的投放申请成功投放的申请记录
            EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
            deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, workitem.getGuid());
            deliveryEntityWrapper.groupBy(SDelivery.COLUMN_GUID_PROFILES);
            List<SDelivery> deliverys = deliveryService.selectList(deliveryEntityWrapper);
            if(deliverys.size() > 0){
                List<Integer> deliveredGuidProfiles = deliverys.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());
                List<SProfiles> profileList = selectBatchIds(deliveredGuidProfiles);
                guidProfile = profileList.stream().map(SProfiles::getGuid).collect(Collectors.toList());
            }
        }
        for (SProfileDetail sProfileDetail : sProfileDetails) {
            if(guidProfile.contains(sProfileDetail.getGuidProfile())){
                sProfileDetail.setDelivered(true);
            }
        }

        return sProfileDetails;
    }

    @Override
    public PackTimeVerify packTimeVerify(String packTimeing, List<SCheck> checks) throws ParseException {

        JSONArray timeArray = JSONArray.parseArray(packTimeing);
        List<String> packTimeSplit = new ArrayList<>();
        timeArray.forEach(object ->{
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if(jsonObject.getString("isOpen").equals(PackTimeIsOpen.TRUE.getValue())){
                packTimeSplit.add(jsonObject.getString("time"));
            }
        });
        //获取今天所有核对记录的投放窗口集合
        List<String> packTimes = checks.stream().map(SCheck::getPackTiming).collect(Collectors.toList());
        //获取当前时间
        Date date = new Date();
        //将时间格式定为时分
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("HH:mm");
        //获取当前时间的字符串时分格式
        String dateString = simpleDateFormat.format(date);
        //将时间转换成时间戳
        long nowDate = simpleDateFormat.parse(dateString).getTime();
        //保存可选时间的窗口集合
        List<String> bigPackTimeList = new ArrayList<>();
        //保存不可选的时间窗口集合
        List<String> smallPackTimeList = new ArrayList<>();
        //定义空投放时间
        Date deliveryTime = null;
        //循环所有窗口判断是否大于当前的时间，有大于的保存
        for(String packTime:packTimeSplit){
            try {
                //时间戳比较
                if(nowDate < simpleDateFormat.parse(packTime).getTime()){
                    //判断核对记录中是否有此窗口
                    if(packTimes.contains(packTime)){
                        smallPackTimeList.add(packTime);
                    }else{
                        bigPackTimeList.add(packTime);
                    }
                }else{
                    smallPackTimeList.add(packTime);
                }
            } catch (ParseException e) {
                throw new DeveloperException("打包窗口不是时间格式的!");
            }
        }
        List<PackTimeDetail> packTimeDetails = new ArrayList<>();
        //判断今天是否有大于当前时间的窗口
        if(bigPackTimeList.size() > 0){
            deliveryTime = date;
            //把小于当前时间的打包窗口置为不可选状态
            if(smallPackTimeList.size() > 0){
                smallPackTimeList.forEach(time ->{
                    PackTimeDetail packTimeDetail = new PackTimeDetail();
                    packTimeDetail.setPackTime(time);
                    packTimeDetail.setIsOptions(OptionsPackTime.NO);
                    packTimeDetails.add(packTimeDetail);
                });
            }
            //把最近当前时间的打包窗口置为默认
            for(int i = 0;i < bigPackTimeList.size();i++){
                PackTimeDetail packTimeDetail = new PackTimeDetail();
                if(i == 0){
                    packTimeDetail.setPackTime(bigPackTimeList.get(i));
                    packTimeDetail.setIsOptions(OptionsPackTime.DEFALIT);
                }else {
                    packTimeDetail.setPackTime(bigPackTimeList.get(i));
                    packTimeDetail.setIsOptions(OptionsPackTime.YES);
                }
                packTimeDetails.add(packTimeDetail);
            }
        }else{
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            //+1今天的时间加一天
            calendar.add(Calendar.DAY_OF_MONTH, +1);
            deliveryTime = calendar.getTime();
            for(int i = 0;i < packTimeSplit.size();i++){
                PackTimeDetail packTimeDetail = new PackTimeDetail();
                if(i == 0){
                    packTimeDetail.setPackTime(packTimeSplit.get(i));
                    packTimeDetail.setIsOptions(OptionsPackTime.DEFALIT);
                }else {
                    packTimeDetail.setPackTime(packTimeSplit.get(i));
                    packTimeDetail.setIsOptions(OptionsPackTime.YES);
                }
                packTimeDetails.add(packTimeDetail);
            }
        }
        PackTimeVerify packTimeVerify = new PackTimeVerify();
        packTimeVerify.setDeliveryTime(deliveryTime);
        packTimeVerify.setPackTimeDetails(packTimeDetails);

        return packTimeVerify;
    }

    @Override
    public List<SProfileDetail> addToNewProfile(Integer guidWorkitem) {
        List<SProfileDetail> profileDetails = profileAllPackTimeVerify(guidWorkitem);

        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,guidWorkitem);
        List<SDelivery> deliverys = deliveryService.selectList(deliveryEntityWrapper);

        List<Integer> guidProfile = deliverys.stream().map(SDelivery::getGuidProfiles).collect(Collectors.toList());

        for (SProfileDetail sProfileDetail : profileDetails) {
            if(guidProfile.contains(sProfileDetail.getGuidProfile())){
                sProfileDetail.setDelivered(true);
            }
        }

        return profileDetails;
    }

    @Override
    public SProfilesGeneralDetail selectProfilesGeneral(Integer guidProfile) {
        SProfilesGeneralDetail profilesGeneralDetail = new SProfilesGeneralDetail();
        SProfiles profiles = selectById(guidProfile);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息详情!");
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT, BranchForWhat.RELEASE);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS, profiles.getGuid());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() == 0){
            profilesGeneralDetail.setBranch(null);
        }else{
            SBranch branch = branchService.selectById(branchMappings.get(0).getGuidBranch());
            profilesGeneralDetail.setBranch(branch);
        }
        profilesGeneralDetail.setProfiles(profiles);
        profilesGeneralDetail.setDeliveryCount(selectProfilesDeliveryCount(profiles.getGuid()));
        profilesGeneralDetail.setDeliveryResultCountDetails(selectDeliveryStatusClassify(profiles.getGuid()));
        profilesGeneralDetail.setWorkitemCount(selectPutWorkitemCount(profiles.getGuid()));
        profilesGeneralDetail.setWorkTypeCount(selectWorkTypeCount(profiles.getGuid()));

        return profilesGeneralDetail;
    }

    @Override
    public void insertBranch(String guid, SBranch branch) throws SVNException {
        SProfiles profiles = selectById(guid);
        if (profiles == null) {
            throw new DeveloperException(guid + "对应环境已删除或不存在！");
        }
        EntityWrapper<SBranch> branchEntityWrapper = new EntityWrapper<>();
        branchEntityWrapper.eq(SBranch.COLUMN_FULL_PATH, branch.getFullPath());
        List<SBranch> branches = branchService.selectList(branchEntityWrapper);
        if(branches.size() > 0){
            throw new DeveloperException("该分支路径已存在，请重新填写！");
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper
                .eq(SBranchMapping.COLUMN_GUID_OF_WHATS, guid)
                .eq(SBranchMapping.COLUMN_FOR_WHAT, branch.getBranchType());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if (!CollectionUtils.isEmpty(branchMappings)) {
            throw new DeveloperException("该环境已经关联分支，不能重复添加！");
        }

        String message = String.format("[artf%s]:建分支", profiles.getArtf());
        long revision = svnKitService.doMkDir(branch.getFullPath(), message);
        try {
            branch.setBranchType(BranchType.RELEASE);
            branch.setCurrVersion((int) revision);
            branch.setLastVersion((int) revision);
            branchService.insert(branch);
            SBranchMapping sBranchMapping = new SBranchMapping();
            sBranchMapping.setAllotTime(new Date());
            sBranchMapping.setForWhat(BranchForWhat.RELEASE);
            sBranchMapping.setStatus(BranchMappingStatus.TAKE);
            sBranchMapping.setGuidBranch(branch.getGuid());
            sBranchMapping.setGuidOfWhats(Integer.valueOf(guid));
            branchMappingService.insert(sBranchMapping);
        } catch (Exception e) {
            svnKitService.doDelete(branch.getFullPath(), message + "异常回滚！");
            throw e;
        }
    }

    @Override
    public void insertProjects(String guid, List<String> projectGuids) throws SVNException {
        SProfiles profiles = selectById(guid);
        if (profiles == null) {
            throw new DeveloperException(guid + "对应环境已删除或不存在！");
        }
        List<Map> maps = branchService.selectListByForWhatIds(BranchForWhat.RELEASE, Collections.singletonList(guid));
        if (CollectionUtils.isEmpty(maps)) {
            throw new DeveloperException(guid + "对应环境没有关联分支");
        }
        String destUrl = maps.get(0).get("fullPath").toString();

        EntityWrapper<SProject> wrapper = new EntityWrapper<>();
        wrapper.in(SProject.COLUMN_GUID, projectGuids);
        List<SProject> sProjects = projectService.selectList(wrapper);
        String[] sourceUrls = new String[sProjects.size()];
        for (int i = 0; i < sProjects.size(); i++) {
            if (!projectGuids.contains(sProjects.get(i).getGuid().toString())) {
                throw new DeveloperException(guid + "对应工程已删除或不存在！");
            }
            sourceUrls[i] = sProjects.get(i).getFullPath();
        }
        String message = String.format("[artf%s]:拉工程", profiles.getArtf());
        svnKitService.doCopy(sourceUrls, destUrl, message);
    }

    @Override
    public ProjectDetail selectProjects(Integer guid) throws SVNException {
        SProfiles profiles = selectById(guid);
        if (profiles == null) {
            throw new DeveloperException(guid + "对应环境已删除或不存在！");
        }
        List<Map> maps = branchService.selectListByForWhatIds(BranchForWhat.RELEASE, Collections.singletonList(guid));
        if (CollectionUtils.isEmpty(maps)) {
            throw new DeveloperException(guid + "对应环境没有关联分支");
        }
        List<String> dir = svnKitService.getDir(maps.get(0).get("fullPath").toString());
        List<SProject> sProjects = projectService.selectProjectAll();
        Map<Boolean, List<SProject>> collect = sProjects.stream()
                .collect(Collectors.groupingBy(p -> dir.contains(p.getProjectName())));
        ProjectDetail projectDetail = new ProjectDetail();
        projectDetail.setOwn(collect.get(true) != null ? collect.get(true) : Collections.EMPTY_LIST);
        projectDetail.setOthers(collect.get(false) != null ? collect.get(false) : Collections.EMPTY_LIST);
        return projectDetail;
    }

    /**
     * 查询此环境所成功投放过的工作项明细
     * @return
     */
    @Override
    public Page<SWorkitem> selectPutWorkitemDetail(Integer guidProfiles, Page<SWorkitem> page,
                                                   EntityWrapper<SWorkitem> wrapper){

        return page.setRecords(this.baseMapper.selectPutWorkitemDetail(guidProfiles, page, wrapper));
    }

    /**
     * 统计此环境有多少工作项投放
     * @param guidProfile
     * @return
     */
    public int selectPutWorkitemCount(Integer guidProfile){

        return this.baseMapper.selectPutWorkitemCount(guidProfile).size();
    }

    /**
     * 此环境投放过的工作项的工作项类型分类统计
     * @param guidProfiles
     * @return
     */
    public List<WorkTypeCountDetail> selectWorkTypeCount(Integer guidProfiles){
        List<WorkTypeCountDetail> workTypeCountDetails = this.baseMapper.selectWorkTypeCount(guidProfiles);
        //continue here:循环标志
        here:
        for (WorkType workType:WorkType.values()){
            if (workTypeCountDetails.size() > 0){
                for (WorkTypeCountDetail workTypeCountDetail:workTypeCountDetails){
                    if(workTypeCountDetail.getWorkType().equals(workType)){
                        continue here;
                    }
                }
            }
            WorkTypeCountDetail workTypeCountDetail = new WorkTypeCountDetail();
            workTypeCountDetail.setCount(0);
            workTypeCountDetail.setWorkType(workType);
            workTypeCountDetails.add(workTypeCountDetail);
        }
        return workTypeCountDetails;
    }

    /**
     * 统计此运行环境有多少投放申请
     * @param guidProfiles
     * @return
     */
    public int selectProfilesDeliveryCount(Integer guidProfiles){

        return this.baseMapper.selectDeliveryCount(guidProfiles);
    }

    /**
     * 查询此运行环境的投放申请按状态分类
     * @param guidProfiles
     * @return
     */
    public List<DeliveryResultCountDetail> selectDeliveryStatusClassify(Integer guidProfiles){
        DeliveryResult[] deliveryResults = DeliveryResult.values();
        //获取数据库中已有投放状态的分类数量
        List<DeliveryResultCountDetail> deliveryStatusClassify =
                this.baseMapper.selectProfilesDeliveryStatusClassify(guidProfiles);
        //将没有申请状态的加上
        here:
        for (DeliveryResult deliveryResult:deliveryResults){
            for(DeliveryResultCountDetail resultCountDetail:deliveryStatusClassify){
                if(deliveryResult.getValue().equals(resultCountDetail.getDeliveryResult())){
                    continue here;
                }
            }
            //将没有投放状态的数量设置为0
            DeliveryResultCountDetail resultCountDetail = new DeliveryResultCountDetail();
            resultCountDetail.setCount(0);
            resultCountDetail.setDeliveryResult(deliveryResult.getValue().toString());
            deliveryStatusClassify.add(resultCountDetail);
        }
        return deliveryStatusClassify;
    }

    @Override
    public List<Map<String, String>> selectPeriodDeliverysGroupDate(int dayNum,Integer guidProfiles){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> deliveryTimes = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        //循环获取当前天与 dayNum:天数 天前的所有日期
        for (int i = 0;i < dayNum; i++){
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, -i);
            deliveryTimes.add(format.format(calendar.getTime()));
            calendar.clear();
        }
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -dayNum);
        Date selectDate = calendar.getTime();
        //获取与 dayNum:多少天前的每天投放数量
        List<DeliveryResultCountDetail> deliveryResultCountDetails =
                this.baseMapper.selectPeriodDeliverys(selectDate, guidProfiles);

        List<Map<String, String>> deliveredDetail = new ArrayList<>();
        for (String time:deliveryTimes){
            Map<String, String> map = new HashMap<>();
            map.put("time", time);
            //here: 跳转循环标识,查询到数据有此类型以及日期是一致的，添加后跳出本次循环
            here:
            for(WorkType workType:WorkType.values()){
                //循环日期已有投放的数量
                for (DeliveryResultCountDetail countDetail:deliveryResultCountDetails){
                    if(countDetail.getWorkType().equals(workType) &&
                            format.format(countDetail.getDeliveryTime()).equals(time)){
                        map.put(workType.getValue().toString(), String.valueOf(countDetail.getCount()));
                        continue here;
                    }
                }
                //将当天没有投放申请的申请数设置为0
                map.put(workType.getValue().toString(), "0");
            }
            deliveredDetail.add(map);
        }


        return deliveredDetail;
    }

    @Override
    public List<DeliveryProjectDetail> selectDeliveryDetailByProWorkGuid(Integer guidProfiles, Integer guidWorkitem) {

        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_GUID_WORKITEM, guidWorkitem)
                            .eq(SRepeal.COLUMN_GUID_PROFILES, guidProfiles);
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);

        List<SRepealList> repealLists = new ArrayList<>();
        if (repeals.size() > 0){
            //获取延期投产申请的guid集合
            List<Integer> guidRepeals = repeals.stream().map(SRepeal::getGuid).collect(Collectors.toList());

            EntityWrapper<SRepealList> repealListEntityWrapper = new EntityWrapper<>();
            repealListEntityWrapper.in(SRepealList.COLUMN_GUID_REPEAL, guidRepeals)
                                    .eq(SRepealList.COLUMN_DELIVERY_STATUS, DeliveryStatus.NOTLAUNCH);
            repealLists = repealListService.selectList(repealListEntityWrapper);
        }

        EntityWrapper<SStandardList> deliveryListEntityWrapper = new EntityWrapper<>();
        deliveryListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM, guidWorkitem);
        //判断是否有延期投产的代码未再次投放，如果有就去除掉
        if(repealLists.size() > 0){
            //获取延期投产代码路径明细集合
            List<String> fullPaths = repealLists.stream().map(SRepealList::getFullPath).collect(Collectors.toList());

            deliveryListEntityWrapper.notIn(SDeliveryList.COLUMN_FULL_PATH, fullPaths);
        }
        List<SStandardList> standardLists = standardListService.selectList(deliveryListEntityWrapper);
        List<DeliveryProjectDetail> deliveryDetail = DeliveryProjectDetail.getStandardDetail(
                standardLists,projectService.selectProjectAll());
        return deliveryDetail;
    }

    @Override
    public List<DeliveryProfilesDetail> selectProfilesDeliveryCount() {

        return this.baseMapper.selectProfilesDeliveryCount();
    }

    @Override
    public Page<SStandardList> selectStandardByItemGuidProGuid(Integer guidProfiles, Integer guidWorkitem,
                                                               Page<SStandardList> page,
                                                               EntityWrapper<SStandardList> wrapper) {
        SProfiles profiles = selectById(guidProfiles);
        if(profiles == null){
            throw new DeveloperException("查询不到此运行环境的信息!");
        }
        return workitemService.selectStandardListAll(guidWorkitem, page, wrapper);
    }

    @Override
    public  Boolean updateRepeal(ProfileUpdateIsRepeal req){
        Integer guid = req.getGuid();
        Boolean repeal = req.isRepeal();
        List<SProfiles> resultList =  selectProfilesAll();
        if(resultList.size() > 0 ){
            for (SProfiles profile:resultList
                 ) {
                if(guid.equals( profile.getGuid())){
                    profile.setIsRepeal(repeal.toString());
                }else{
                    profile.setIsRepeal("false");
                }
            }
            updateAllColumnBatchById(resultList);
        }
        return true;
    }

    @Override
    public void checkoutCode(Integer guidProfiles) throws SVNException {
        //查询允许环境的信息
        SProfiles profiles = selectById(guidProfiles);
        if (profiles == null) {
            throw new DeveloperException(guidProfiles + "对应环境已删除或不存在！");
        }
        //查询运行环境关联的分支信息
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT, BranchForWhat.RELEASE);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS, profiles.getGuid());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() == 0){
            throw new DeveloperException(guidProfiles+"查询不到此运行环境关联的分支信息!");
        }
        //获取分支对象
        SBranch branch = branchService.selectById(branchMappings.get(0).getGuidBranch());
        //调用svnkit的checkout API对象环境代码进行下载
        svnKitService.checkoutProfilesCode(branch.getFullPath());
    }
}

